<!--
 - Author : wang885298.
 - Date   : 2018/7/13.
 - File   : 2d.
 -->

<template>
        <el-container>
          <el-main v-show="mapType===2">
            <div id="l-map"></div>
            <div id="r-result" class="result">请输入:<input type="text" id="suggestId" size="20" value="百度"
                                                         style="width:150px;"/></div>
            <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
          </el-main>
          <el-main v-show="mapType===0">
            <!--高德地图-->
            <div class="anchors">
              <div class="anchors-left">
                <div class="zhiZ" @click="listener()">指针</div>
              </div>
              <div class="anchors-list">
                <div class="item" :id="item.id" v-for="(item,index) in anchorsList" @click="listener(item)">
                  {{item.name}}
                </div>
              </div>
            </div>
            <div id="container"></div>
            <div class="anchorsBar" v-show="infoShow">
              <el-card class="box-card">
                <div slot="header" class="clearfix box-header">
                  <span>摄像头锚点信息</span>
                </div>
                <div class="text item">
                  <el-form label-position="left" label-width="55px" :model="achorsInfo">
                    <el-form-item label="名称：">
                      <el-input size="small" v-model="achorsInfo.name"></el-input>
                    </el-form-item>
                    <el-form-item label="备注：">
                      <el-input :rows="4" type="textarea" v-model="achorsInfo.remark"></el-input>
                    </el-form-item>
                    <div class="lab-title">锚点坐标值：</div>
                    <el-form-item label="X：">
                      <el-input size="small" v-model="achorsInfo.langX"
                          @input="lngLet(achorsInfo.langX, 'x')"></el-input>
                    </el-form-item>
                    <el-form-item label="Y：">
                      <el-input size="small" v-model="achorsInfo.langY"
                          @input="lngLet(achorsInfo.langY, 'Y')"></el-input>
                    </el-form-item>
                    <div>当前锚点默认地图比例尺：</div>
                    <div class="select">
                      <el-select size="small" v-model="achorsInfo.zoom" placeholder="锚点默认地图比例尺">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
                      </el-select>
                    </div>
                    <div class="btn-group">
                      <el-row>
                        <el-button class="left" size="medium" round>保存</el-button>
                        <el-button class="right" size="medium" round>删除</el-button>
                      </el-row>
                    </div>
                  </el-form>
                </div>
              </el-card>

              <div class="btn-group gl">
                <el-row>
                  <el-button class="left" size="medium" round>关联</el-button>
                  <el-button class="right" size="medium" round>预览</el-button>
                </el-row>
              </div>
            </div>
            <div class="loaction">
              <div class="loaction-search clearfix">
                <div class="loaction-search-left">
                  <el-form label-position="top">
                    <el-form-item label="关键字定位地图中心点：">
                      <el-input size="small" placeholder="输入地址" id="pickerInput" v-model="searchVal" :clearable="true"></el-input>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="loaction-search-right">
                  <el-form label-position="top">
                    <el-form-item label="坐标定位地图中心：" style="text-align: left;">
                      <el-col class="line" :span="2" style="text-align: left">X:</el-col>
                      <el-col :span="7">
                        <el-form-item>
                          <el-input size="small" placeholder="X:" v-model="lnglat[0]"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col class="line" :span="2" style="text-align: center">Y:</el-col>
                      <el-col :span="7">
                        <el-form-item>
                          <el-input size="small" placeholder="Y:" v-model="lnglat[1]"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6" style="text-align: right">
                        <el-button class="pos-btn" type="primary" round size="small" @click="setZoomCenter(12, lnglat)">
                          定位
                        </el-button>
                      </el-col>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </el-main>
          <el-main v-show="mapType===1">
            <!--高德地图-->
            <div class="anchors">
              <div class="anchors-left">
                <div class="zhiZ" @click="listener()">指针</div>
              </div>
              <div class="anchors-list">
                <div class="item" :id="item.id" v-for="(item,index) in anchorsList" @click="listener(item)">
                  {{item.name}}
                </div>
              </div>
            </div>
            <div id="container3D"></div>
            <div class="anchorsBar">
              <el-card class="box-card">
                <div slot="header" class="clearfix box-header">
                  <span>摄像头锚点信息</span>
                </div>
                <div class="text item">
                  <el-form label-position="left" label-width="55px" :model="achorsInfo">
                    <el-form-item label="名称：">
                      <el-input size="small" v-model="achorsInfo.name"></el-input>
                    </el-form-item>
                    <el-form-item label="备注：">
                      <el-input :rows="4" type="textarea" v-model="achorsInfo.remark"></el-input>
                    </el-form-item>
                    <div class="lab-title">锚点坐标值：</div>
                    <el-form-item label="X：">
                      <el-input size="small" v-model="achorsInfo.langX"></el-input>
                    </el-form-item>
                    <el-form-item label="Y：">
                      <el-input size="small" v-model="achorsInfo.langY"></el-input>
                    </el-form-item>
                    <div>当前锚点默认地图比例尺：</div>
                    <div class="select">
                      <el-select size="small" v-model="achorsInfo.zoom" placeholder="锚点默认地图比例尺">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
                      </el-select>
                    </div>
                    <div class="btn-group">
                      <el-row>
                        <el-button class="left" size="medium" round>保存</el-button>
                        <el-button class="right" size="medium" round>删除</el-button>
                      </el-row>
                    </div>
                  </el-form>
                </div>
              </el-card>

              <div class="btn-group gl">
                <el-row>
                  <el-button class="left" size="medium" round>关联</el-button>
                  <el-button class="right" size="medium" round>预览</el-button>
                </el-row>
              </div>
            </div>
            <div class="loaction">
              <div class="loaction-search clearfix">
                <div class="loaction-search-left">
                  <el-form label-position="top">
                    <el-form-item label="关键字定位地图中心点：">
                      <el-input size="small" placeholder="输入地址" id="pickerInput3D" v-model="searchVal3D" :clearable="true"></el-input>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="loaction-search-right">
                  <el-form label-position="top">
                    <el-form-item label="坐标定位地图中心：" style="text-align: left">
                      <el-col class="line" :span="2" style="text-align: center">X:</el-col>
                      <el-col :span="7">
                        <el-form-item>
                          <el-input size="small" placeholder="X:" v-model="lnglat[0]"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col class="line" :span="2" style="text-align: center">Y:</el-col>
                      <el-col :span="7">
                        <el-form-item>
                          <el-input size="small" placeholder="Y:" v-model="lnglat[1]"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6" style="text-align: right">
                        <el-button class="pos-btn" type="primary" round size="small" @click="setZoomCenter(12, lnglat)">
                          定位
                        </el-button>
                      </el-col>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </el-main>
        </el-container>
</template>

<script>
//  import throttle from '../util.js'
  export default {
    data() {
      return {
        map: null,
        gdMap: null,
        searchVal: '',
        searchVal3D: '',
        gdMap3D: null,
        mapType: parseInt(this.$route.query.mapType) || 0,//地图类型：0高德，1百度
        iconImage: '',//锚点元素图标
        anchorsList: [
          {
            name: '治安点',
            type: '1',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
            id: 'a'
          },
          {
            name: '鹰眼',
            type: '2',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_r.png',
            id: 'b'
          },
          {
            name: '摄像头',
            type: '3',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
            id: 'c'
          },
          {
            name: '治安点1',
            type: '4',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_r.png',
            id: 'd'
          },
          {
            name: '鹰眼1',
            type: '5',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
            id: 'e'
          },
          {
            name: '摄像头1',
            type: '6',
            icon: '//webapi.amap.com/theme/v1.3/markers/b/mark_r.png',
            id: 'f'
          }
        ], // 锚点元素列表
        pointType: '', //锚点类型
        achorsInfo: {
          name: '',
          remark: '',
          langX: '',
          langY: '',
          zoom: ''
        },// 锚点信息栏
        lnglat: [],
        marker: {},
        pointMarker: {},
        tmpLngLat: {
          langX: '',
          langY: ''//临时锚点坐标
        },
        infoShow: false //锚点信息栏是否显示
      }
    },
    watch: {
      mapType(cur, old) {
        if (!cur && !this.gdMap) {
          this.gdMap = new AMap.Map('container', {
            zoom: 10,//级别
            resizeEnable: true,
            mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
            viewMode: '2D' // 使用3D视图
          })
          this.map = this.gdMap
          // 获取当前位置中心点坐标
          this.lnglat = [this.gdMap.getCenter().lng, this.gdMap.getCenter().lat]
          this.gadMap(this.gdMap, 'pickerInput')
        }
        if (cur === 1 && !this.gdMap3D) {
          let gMapInit = () => {
            this.gdMap3D = new AMap.Map('container3D', {
              zoom: 10,//级别
              resizeEnable: true,
              mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
              viewMode: '3D' // 使用3D视图
            })
            this.map = this.gdMap3D
            // 获取当前位置中心点坐标
            this.lnglat = [this.gdMap3D.getCenter().lng, this.gdMap3D.getCenter().lat]
            this.gadMap(this.gdMap3D, 'pickerInput3D')
          }
          setTimeout(() => {
            gMapInit()
          }, 0)
        }
      }
    },
    beforeRouteUpdate(to, from, next) {
      console.log(to.name, to.path, from.name, from.path)
      this.mapType = parseInt(to.query.mapType)
      this.map = this.mapType ? this.gdMap3D : this.gdMap
      next()
    },
    mounted() {
      this.lngLet = this.$utils.throttle(this.change, 600)
      if (!this.mapType) {
        this.gdMap = new AMap.Map('container', {
          zoom: 10,//级别
          resizeEnable: true,
          mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
          viewMode: '2D' // 不使用3D视图
        })
        this.map = this.gdMap
        // 获取当前位置中心点坐标
        this.lnglat = [this.gdMap.getCenter().lng, this.gdMap.getCenter().lat]
        this.gadMap(this.gdMap, 'pickerInput')
      } else if (this.mapType === 1) {
        this.gdMap3D = new AMap.Map('container3D', {
          zoom: 10,//级别
          resizeEnable: true,
          mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
          viewMode: '3D' // 使用3D视图
        })
        this.map = this.gdMap3D
        // 获取当前位置中心点坐标
        this.lnglat = [this.gdMap3D.getCenter().lng, this.gdMap3D.getCenter().lat]
        this.gadMap(this.gdMap3D, 'pickerInput3D')
      } else {
        this.baiduMap()
      }
    }
    ,
    methods: {
      G(id) {
        return document.getElementById(id)
      },
      /**
       * 百度地图
       */
      baiduMap() {
        let map = new BMap.Map('l-map')
        map.centerAndZoom('北京', 12)                   // 初始化地图,设置城市和地图级别。
        let G = this.G('searchResultPanel')
        map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        //建立一个自动完成的对象
        let ac = new BMap.Autocomplete({
          'input': 'suggestId'
          , 'location': map
        })
        ac.addEventListener('onhighlight', e => {  //鼠标放在下拉列表上的事件
          let str = ''
          let _value = e.fromitem.value
          let value = ''
          if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business
          }
          str = 'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value

          value = ''
          if (e.toitem.index > -1) {
            _value = e.toitem.value
            value = _value.province + _value.city + _value.district + _value.street + _value.business
          }
          str += '<br />ToItem<br />index = ' + e.toitem.index + '<br />value = ' + value
          G.innerHTML = str
        })
        let myValue
        ac.addEventListener('onconfirm', e => {    //鼠标点击下拉列表后的事件
          let _value = e.item.value
          myValue = _value.province + _value.city + _value.district + _value.street + _value.business
          G.innerHTML = 'onconfirm<br />index = ' + e.item.index + '<br />myValue = ' + myValue
          map.clearOverlays()    //清除地图上所有覆盖物
          function myFun () {
            let pp = local.getResults().getPoi(0).point    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18)
            map.addOverlay(new BMap.Marker(pp))    //添加标注
          }

          let local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
          })
          local.search(myValue)
        })
      },
      /**
       * 高德地图加载
       */
      gadMap (ctx, inputId) {
        //显示比例尺
        this.scale(ctx)
        this.zoom(ctx)
        this.point(ctx)
        this.KeywordLocationMapCenterPoint(ctx, inputId)
      },
      /**
       * 显示比例尺
       */
      scale (ctx){
        AMap.plugin(['AMap.Scale'], function () {
          ctx.addControl(new AMap.Scale({
            position: 'tl',
          }));
        })
      },
      /**
       * 显示缩放
       */
      zoom (ctx){
        AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
          let zoomCtrl1 = new BasicControl.Zoom({
            position: 'tl',
            theme: 'dark'
          })
          ctx.addControl(zoomCtrl1);
        })
      },
      /**
       * 地图上打点
       */
      point (ctx){
        ctx.on('click', e => {
          //添加点击事件,传入对象名，事件名，回调函数
          if (this.iconImage !== '') {
            let marker = new AMap.Marker({
              position: e.lnglat,
              map: ctx,
              draggable: true,
              cursor: 'move',
              icon: new AMap.Icon({
                size: new AMap.Size(19, 33),  //图标大小
                image: this.iconImage,
                imageOffset: new AMap.Pixel(0, 0),
                imageSize: new AMap.Size(19, 33)
              })
            })
            let extData = {type: this.pointType}
            marker.setExtData(extData) //给标记点添加type属性
            this.infoShow = true //显示锚点栏

            this.achorsInfo = {langX: e.lnglat.lng, langY: e.lnglat.lat}
            this.tmpLngLat = {langX: e.lnglat.lng, langY: e.lnglat.lat}

            this.pointMarker = marker
            marker.on('dragend', e => { //拖动标注点结束后的坐标
              this.achorsInfo = {langX: e.lnglat.lng, langY: e.lnglat.lat}
              this.tmpLngLat = {langX: e.lnglat.lng, langY: e.lnglat.lat}
            })

            marker.on('mousedown', e => { //点击标注点的坐标
              this.pointMarker = e.target
              let lnglat = e.target.getPosition()
              this.achorsInfo = {langX: lnglat.lng, langY: lnglat.lat}
              this.tmpLngLat = {langX: lnglat.lat, langY: lnglat.lat}
            })
          }
        })
      },
      /**
       * 改变坐标值标注跟着改变
       */
      change (lngLet, type) {
        if (type === 'x') {
          //判断经度值是否正确
          let longreg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/
          if(!longreg.test(lngLet)){
            this.$message.error('经度值为：180到-180，整数部分为0-180,小数部分为0到6位!')
            this.achorsInfo.langX = this.tmpLngLat.langX
          } else {
            this.achorsInfo.langX = lngLet
            this.pointMarker.setPosition([parseFloat(this.achorsInfo.langX), parseFloat(this.achorsInfo.langY)])
          }
        } else {
          //判断纬度值是否正确
          let latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
          if(!latreg.test(lngLet)){
            this.$message.error('纬度值为：90到-90，整数部分为0-90,小数部分为0到6位!')
            this.achorsInfo.langY = this.tmpLngLat.langY
          } else {
            this.achorsInfo.langY = lngLet
            this.pointMarker.setPosition([parseFloat(this.achorsInfo.langX), parseFloat(this.achorsInfo.langY)])
          }
        }
      },
      /**
       * 改变鼠标样式
       * @param item
       */
      listener(item) {
        if (item) {
          this.map.setDefaultCursor("url('" + item.icon + "'),pointer")
          this.iconImage = item.icon
          this.pointType = item.type
          let arr = this.map.getAllOverlays() //获取地图上的所有标注点
          if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) { //点击相应的锚点类型，显示隐藏相应的点标记
              let type = arr[i].getExtData().type
              if (type !== this.pointType) {
                if(type !== 'center') {
                  arr[i].hide()
                }
              } else {
                arr[i].show()
              }
            }
          }
        } else {
          this.map.setDefaultCursor("default")
          this.iconImage = ''
        }
      },
      /**
       * 关键字定位地图中心点
       */
      KeywordLocationMapCenterPoint(ctx, inputId) {
        AMapUI.loadUI(['misc/PoiPicker'], PoiPicker => {
          let poiPicker = new PoiPicker({
            input: inputId
          })
          //初始化poiPicker
          this.marker = new AMap.Marker()
          //选取了某个POI
          console.log('this.gdMap', ctx)
          poiPicker.on('poiPicked', poiResult => {
            let poi = poiResult.item
            this.marker.setMap(ctx)
            if (inputId === 'pickerInput') {
              this.searchVal = poi.name
            } else {
              this.searchVal3D = poi.name
            }
            if (!poi.location) return
            this.marker.setMap(ctx)
            this.marker.setPosition(poi.location)
            let extData = {type: 'center'}
            this.marker.setExtData(extData) //给标记点添加type属性
            ctx.setZoomAndCenter(19, this.marker.getPosition())
          })
        })
      },
      /**
       * 高德地图定坐标位功能
       * @param zoom {Number} 设置缩放大小
       * @param center {Arrary} 坐标经纬度（[199, 26]）
       */
      setZoomCenter(zoom, center) {
        center = [parseFloat(center[0]), parseFloat(center[1])]
        this.map.setZoomAndCenter(zoom, center)
        this.marker.setPosition(center)
        this.marker.setMap(null)
        this.marker.setMap(this.map);
        let extData = {type: 'center'}
        this.marker.setExtData(extData) //给标记点添加type属性
      }
    }
  }
</script>

<style lang="less">
  #l-map {
    height: 100%;
  }

  .result {
    position: fixed;
    background-color: #fff;
    top: 90px;
    left: 200px;
    padding: 10px;
    width: 100%;
  }

  #container, #container3D {
    width: 100%;
    height: 100%;
    margin: 0;
    font-size: 13px;
    /*缩放样式*/
    .amap-ui-control-position-lt, .amap-ui-control-position-tl {
      top: 180px !important;
      left: 40px !important;
    }
    .amap-ui-control-zoom {
      width: 40px !important;
    }
    .amap-ui-control-zoom a, .amap-ui-control-zoom-num {
      width: 40px !important;
      height: 50px !important;
      line-height: 50px !important;
    }
    /*比例尺样式*/
    .amap-scalecontrol {
      color: #fff;
      top: 300px;
      left: 30px;
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-header {
    font-size: 18px;
  }

  /*锚点信息*/
  .anchorsBar {
    position: fixed;
    right: 25px;
    z-index: 999;
    top: 185px;
    text-align: left;
    .text {
      font-size: 14px;
    }

    .box-card {
      width: 310px;
      color: #fff;
      border: 2px solid !important;
      border-image: -webkit-linear-gradient(#3f4249, #00ffff, #3f4249) 30 30 !important;
      border-image: -moz-linear-gradient(#3f4249, #00ffff, #3f4249) 30 30 !important;
      border-image: linear-gradient(#3f4249, #00ffff, #3f4249) 30 30 !important;
      background-color: #3f4249 !important;
      .el-card__header {
        border-bottom: none !important;
        padding: 18px 20px 2px !important;
      }
      .el-form-item__label {
        color: #fff !important;
      }
    }
    .lab-title {
      margin-bottom: 15px;
    }
    .select {
      margin: 10px 0;
      .el-select {
        width: 100%;
      }
    }
    .btn-group{
      padding: 20px 5px 10px 5px;
      text-align: center;
      .left{
        float: left;
        color: #fff;
        padding: 10px 40px;
        background: -webkit-linear-gradient(left, #088eec , #17b3e7) !important; /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(right, #088eec, #17b3e7) !important; /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(right, #088eec, #17b3e7) !important; /* Firefox 3.6 - 15 */
        background: linear-gradient(to right, #088eec , #17b3e7) !important; /* 标准的语法（必须放在最后）*/
        border: none;
      }
      .right{
        float: right;
        color: #fff;
        padding: 10px 40px;
        background: none;
        border: 1px solid #5390a3;
      }
    }
    .gl{
      margin-top: 25px;
      background-color: #3f4249;
      padding: 35px 25px;
      border: 2px solid;
      border-image: -webkit-linear-gradient( #3f4249, #00ffff, #3f4249 ) 30 30;
      border-image: -moz-linear-gradient( #3f4249, #00ffff, #3f4249 ) 30 30;
      border-image: linear-gradient( #3f4249, #00ffff, #3f4249 ) 30 30;
    }
  }

  /*搜索定位*/
  .loaction {
    width: 745px;
    position: fixed;
    top: 120px;
    left: 240px;
    z-index: 999;
    color: #fff;
    text-align: left;
    &-search {
      /*width: 100%;*/
      background-color: #3f4249;
      padding: 5px 25px;
      border: 2px solid;
      border-image: -webkit-linear-gradient(#3f4249, #00ffff, #3f4249) 30 30;
      border-image: -moz-linear-gradient(#3f4249, #00ffff, #3f4249) 30 30;
      border-image: linear-gradient(#3f4249, #00ffff, #3f4249) 30 30;
      .el-form-item__label {
        color: #fff;
      }
      .el-form-item {
        margin-bottom: 5px !important;
      }
      .el-form--label-top .el-form-item__label {
        padding: 0 !important;
        line-height: 35px !important;
      }
      &-left {
        float: left;
        width: 30%;
      }
      &-right {
        float: right;
        width: 60%;
        text-align: right;
        .pos-btn {
          padding: 10px 30px;
          background: -webkit-linear-gradient(left, #088eec, #17b3e7) !important; /* Safari 5.1 - 6.0 */
          background: -o-linear-gradient(right, #088eec, #17b3e7) !important; /* Opera 11.1 - 12.0 */
          background: -moz-linear-gradient(right, #088eec, #17b3e7) !important; /* Firefox 3.6 - 15 */
          background: linear-gradient(to right, #088eec, #17b3e7) !important; /* 标准的语法（必须放在最后） */
        }
      }
    }
    .amap-ui-poi-picker-sugg-list {
      color: #999 !important;
      min-width: 300px !important;
    }
    .amap-ui-poi-picker-search-results-container, .amap-ui-poi-picker-sugg-container {
      min-width: 300px !important;
    }
  }
</style>
